package com.zhuna.www.dao.impl;

import com.zhuna.www.constant.UserRole;
import com.zhuna.www.dao.UserDAO;
import com.zhuna.www.po.User;
import com.zhuna.www.util.JDBCutil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDAOImp1 implements UserDAO {
    //新增用户
    @Override
    public int add(User user) throws SQLException{
        String sql = "INSERT INTO user (name, password, role) VALUES (?, ?,?)";
        try (Connection conn = JDBCutil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);) {  //主键自增
            //传参数
            pstmt.setString(1, user.getName());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getRole().name());// 枚举转字符串
            int affectedrows = pstmt.executeUpdate(); // 影响行数
            if (affectedrows > 0) {
            try(ResultSet rs = pstmt.getGeneratedKeys()) {
                if (rs.next()) {
                    return rs.getInt(1);// 返回主键自增值
                }
            }}
        }
        return -1;// 失败返回-1


    }

    //更新用户余额
    @Override
    public int updateWalletBalance(Connection conn,int id, double delta) throws SQLException{
        String sql = "UPDATE user SET wallet_balance = wallet_balance + ? WHERE id = ?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)){
            stmt.setDouble(1, delta);
            stmt.setInt(2, id);
            return stmt.executeUpdate();
        }
    }

    //更新用户信息
    @Override
    public int updateUser(int userId,String newName,String newPassword) throws SQLException {
        // 动态构建 SQL 语句
        List<String> updateFields = new ArrayList<>();
        List<Object> params = new ArrayList<>();
        //判断需要更新的字段
        if (newName != null) {
            updateFields.add("name = ?");
            params.add(newName);
        }
        if (newPassword != null) {
            updateFields.add("password = ?");
            params.add(newPassword); // 注意：密码需要预先加密
        }
        // 如果没有更新的字段，直接返回
        if (updateFields.isEmpty()) {
            throw new IllegalArgumentException("至少需要提供新用户名或新密码");
        }
        String sql = "UPDATE user SET " + String.join(", ", updateFields) + " WHERE id = ?";
        params.add(userId);
        try (Connection conn = JDBCutil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 绑定参数
            for (int i = 0; i < params.size(); i++) {
                stmt.setObject(i + 1, params.get(i));
            }

            return stmt.executeUpdate();
        }
    }

    //删除用户
    @Override
    public int deleteUser(String name) throws SQLException {
        String sql = "DELETE FROM user WHERE name = ?";
        try (Connection conn = JDBCutil.getConnection();
        PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1,name);
            int affectedrows = pstmt.executeUpdate();
            return affectedrows;

        }
    }

    //查询所有用户
    @Override
    public List<User> selectallUser() throws SQLException {
        List<User> users = new ArrayList<>();
        String sql = "SELECT id, name, wallet_balance, role, created_at FROM user ORDER BY created_at DESC";

        try (Connection conn = JDBCutil.getConnection();
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();) {
            while (rs.next()) {
                User user = new User();
                user.setName(rs.getString("name"));
                user.setWallet_balance(rs.getInt("wallet_balance"));
                user.setRole(UserRole.valueOf(rs.getString("role")));

                Timestamp created_at = rs.getTimestamp("created_at");
                user.setCreated_at(created_at);

                users.add(user);

            }
        }
        return users;
    }

    //根据用户名查询用户
    @Override
    public User selectUserByName(String name) throws SQLException {
        String sql = "select * from user where name = ?";
        try (Connection conn = JDBCutil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);) {
            pstmt.setString(1, name);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                System.out.println("查询到该用户");
                return new User(
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getString("password"),
                        UserRole.valueOf(rs.getString("role")),
                        rs.getDouble("wallet_balance")
                );// 返回用户信息
            }else {
                System.out.println("未查询到给用户");
            }
        }return null;
    }

    @Override
    public double getWalletBalanceByname(String name) throws SQLException {
        String sql = "SELECT wallet_balance FROM user WHERE name = ?";
        try (Connection conn = JDBCutil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, name);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getDouble("wallet_balance");
                }
            }
        }
        return -1; // 查询失败或用户不存在
    }


}
